package com.mybatisplus.filters;

import com.mybatisplus.utils.BaseParams;
import com.mybatisplus.utils.ToHttpServletUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*页面请求过滤器*/
@CrossOrigin(value = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE})
@WebFilter(filterName = "PageFilter", urlPatterns = "/pages/*")
public class PageFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException, NullPointerException {
        //签到过滤器
        HttpServletRequest httpServletRequest = ToHttpServletUtil.toHttpServletRequest(request);
        //调用ToHttpServletUtil类封装的toHttpServletXXX(XXX)方法穿入的请求和响应转化成http对应的request对象和response对象
        HttpSession session = httpServletRequest.getSession(false);
        response.setContentType("text/html;charset=utf-8");
        String baseURL = BaseParams.CURRENT_DOMAIN_NAME;//从常量类中获取域名地址
        String url = httpServletRequest.getRequestURL().toString();//从httpServletRequest对象中获取请求发起的url
        if (session != null || url.contains(baseURL + "/pages/Sign_QRcode.html")) {
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            System.out.println("用户已登录=>已放行");
            chain.doFilter(request, response);
        } else {
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            System.out.println("用户未登录=>已拦截用户行为");
            System.out.println("正在使用户重定向到登陆界面");
            response.getWriter().println("<script>alert('登录失效，请重新登录');window.location.href='/';</script>");
        }


    }
}
